import { create } from 'zustand';
import dayjs from 'dayjs';

const generateSalesData = (startDate, endDate) => {
  const data = [];
  const start = dayjs(startDate);
  const end = dayjs(endDate);
  const days = end.diff(start, 'day') + 1;
  
  for (let i = 0; i < days; i++) {
    const date = start.add(i, 'day').format('YYYY-MM-DD');
    data.push({
      date,
      sales: Math.floor(Math.random() * 5000) + 2000,
      orders: Math.floor(Math.random() * 50) + 20,
    });
  }
  
  return data;
};

const mockDishSales = [
  { dishName: 'IPA精酿啤酒', sales: 15680, orders: 320 },
  { dishName: '比利时修道院啤酒', sales: 12450, orders: 180 },
  { dishName: '世涛黑啤', sales: 9850, orders: 280 },
  { dishName: '淡色艾尔', sales: 8760, orders: 220 },
  { dishName: '小麦白啤', sales: 6540, orders: 190 },
];

const mockMemberConsumption = [
  { level: '铂金会员', amount: 28500, count: 12 },
  { level: '金牌会员', amount: 45600, count: 35 },
  { level: '银牌会员', amount: 32400, count: 58 },
  { level: '铜牌会员', amount: 18900, count: 72 },
];

const useAnalyticsStore = create((set, get) => ({
  dateRange: [dayjs().subtract(7, 'day'), dayjs()],
  salesTrend: generateSalesData(dayjs().subtract(7, 'day').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')),
  dishSales: mockDishSales,
  memberConsumption: mockMemberConsumption,
  loading: false,
  
  statistics: {
    totalSales: 0,
    totalOrders: 0,
    avgOrderAmount: 0,
    totalMembers: 0,
  },

  setDateRange: (dateRange) => {
    set({ dateRange });
    get().fetchAnalytics(dateRange);
  },

  fetchAnalytics: async (dateRange) => {
    set({ loading: true });
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      
      const [start, end] = dateRange;
      const salesTrend = generateSalesData(start.format('YYYY-MM-DD'), end.format('YYYY-MM-DD'));
      
      const totalSales = salesTrend.reduce((sum, item) => sum + item.sales, 0);
      const totalOrders = salesTrend.reduce((sum, item) => sum + item.orders, 0);
      const avgOrderAmount = totalOrders > 0 ? totalSales / totalOrders : 0;
      
      set({
        salesTrend,
        statistics: {
          totalSales,
          totalOrders,
          avgOrderAmount,
          totalMembers: mockMemberConsumption.reduce((sum, item) => sum + item.count, 0),
        },
        loading: false,
      });
    } catch (error) {
      set({ loading: false });
    }
  },

  initAnalytics: () => {
    const { dateRange } = get();
    get().fetchAnalytics(dateRange);
  },
}));

export default useAnalyticsStore;
